<template>
  <div class="login-container">
    <h2 class="login-title">用户登录</h2>
    <van-form @submit="handleSubmit">
      <van-cell-group inset>
        <!-- 用户名输入 -->
        <van-field v-model="userName" name="username" label="用户名" placeholder="请输入用户名"
          :rules="[{ required: true, message: '请填写用户名' }]" left-icon="user-o" />

        <!-- 密码输入 -->
        <van-field v-model="password" type="password" name="password" label="密码" placeholder="请输入密码"
          :rules="[{ required: true, message: '请填写密码' }]" left-icon="lock" />
      </van-cell-group>

      <!-- 登录按钮 -->
      <div class="submit-btn">
        <van-button round block type="primary" native-type="submit" color="#1989fa">
          立即登录
        </van-button>
      </div>

      <!-- 在登录按钮后添加注册链接 -->
      <div class="action-links">
        <router-link to="/register" class="register-link">
          <van-button plain type="primary" size="small">
            立即注册
          </van-button>
        </router-link>
      </div>


      <!-- 错误提示 -->
      <van-notice-bar v-if="userStore.error" color="#ee0a24" background="#fff7f8" left-icon="warning-o"
        class="error-notice">
        {{ userStore.error }}
      </van-notice-bar>
    </van-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/stores/userStore'
import { useRouter } from 'vue-router'
import {
  Form as VanForm,
  Field as VanField,
  CellGroup as VanCellGroup,
  Button as VanButton,
  NoticeBar as VanNoticeBar
} from 'vant'

const router = useRouter()
const userStore = useUserStore()

const userName = ref('')
const password = ref('')

const handleSubmit = async () => {
  const success = await userStore.login(userName.value, password.value)
  if (success) {
    router.push('/mine')
  }
}
</script>

<style scoped>
.login-container {
  max-width: 500px;
  margin: 0 auto;
  padding: 2em;
}

.login-title {
  text-align: center;
  color: #1989fa;
  margin-top: 2em;
  margin-bottom: 2rem;
  font-size: 1.5rem;
}

.submit-btn {
  margin: 2rem 1rem;
}

.error-notice {
  margin-top: 1rem;
  border-radius: 8px;
}


.action-links {
  margin-top: 20px;
  text-align: center;
}

.register-link {
  display: inline-block;
  margin: 0 10px;
  
  /* 去除router-link默认样式 */
  text-decoration: none;
}

/* 鼠标悬停效果 */
.van-button--primary.van-button--plain:hover {
  background: #e6f7ff;
}
</style>